﻿CREATE PROCEDURE [dbo].[SupplierInvoiceDocInsert]
(--приходная накладная от поставщика
	@DocDate smalldatetime,
	@DocNumber varchar(20),
	@ContragentId int,
	@ContragentDocDate smalldatetime,
	@ContragentDocNumber varchar(20),
	@PaymentDate smalldatetime,
	@Note varchar(250),
	@MD datetime,
	@MW varchar(50)
)
AS
DECLARE @strMsg nvarchar(500), @intRet int, @intErrCode int, @intNextId int
DECLARE @DocTypeId int,	@DepartmentUserId int

SET NOCOUNT ON

IF (@ContragentId Is Null)
BEGIN
	SELECT @intErrCode = 1, @strMsg = 'Неправильные параметры в вызове процедуры ' + Object_Name(@@Procid) + ' !'
	RAISERROR (@strMsg, 11, @intErrCode)
	RETURN @intErrCode
END
--TODO проверить чтобы контрагент был поставщиком
IF @DocNumber Is Null
BEGIN
	exec [dbo].[GetNextDocNumber] 2, @intRet OUT
	SET @DocNumber = cast( @intRet as varchar(20))
END

IF @DocDate Is Null SET @DocDate = dbo.TodayDate() 
ELSE SET @DocDate = dbo.NormalizeDate(@DocDate)

IF (@ContragentDocDate Is NOT Null) SET @ContragentDocDate = dbo.NormalizeDate(@ContragentDocDate)
IF (@PaymentDate Is NOT Null) SET @PaymentDate = dbo.NormalizeDate(@PaymentDate)

IF (@ContragentDocDate Is NOT Null) AND @ContragentDocDate > @DocDate
BEGIN
	SELECT @intErrCode = 2, 
	@strMsg = 'Дата документа поставщика больше даты приходной накладной!'
	RAISERROR (@strMsg, 11, 1)
	RETURN @intErrCode
END
IF (@PaymentDate Is NOT Null) AND @PaymentDate < @DocDate
BEGIN
	SELECT @intErrCode = 3, 
	@strMsg = 'Дата оплаты д.б. больше даты приходной накладной!'
	RAISERROR (@strMsg, 11, 1)
	RETURN @intErrCode
END

SELECT @DepartmentUserId = Id FROM CD.DepartmentUsers WHERE Login = suser_sname()

EXEC [dbo].[ProcessStatistic] @Note OUTPUT, @MD OUTPUT, @MW OUTPUT
--получение значения идентификатора
EXEC @intRet = dbo.GetNextCounterFor 'Documents', @intNextId OUTPUT
IF @intRet <> 0 RETURN @intRet

	SET NOCOUNT OFF;
INSERT INTO [CA].[Documents] (Id, [DocTypeId], [DocDate], [DocNumber], 
[ContragentId], ContragentDocDate, ContragentDocNumber, PaymentDate, DepartmentUserId,
[Note], [MD], [MW]) 
VALUES (@intNextId, 2, @DocDate, @DocNumber, 
@ContragentId, @ContragentDocDate, @ContragentDocNumber, @PaymentDate, @DepartmentUserId,
@Note, @MD, @MW);
	
SELECT Id, DepartmentId, DocTypeId, DocDate, DocNumber, 
ContragentId, ContragentDocDate, ContragentDocNumber, PaymentDate, 
DepartmentUserId, Note, MD, MW 
FROM CA.Documents WHERE (Id = @intNextId)

RETURN 0

